<template>
    <div>
        <Spin fix v-if="ifSpin">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>附件生成中</div>
        </Spin>
        <Form :label-width="100" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                    <FormItem label="创建时间：">
                        <DatePicker v-model="formInline.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择查询时间（开始，结束）"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="组织机构：">
                        <cascaderDom ref="existOrg" @setOrgInfo="setOrgName" :orgTree="true" :currentOrgId = "dataToView.companyId" :currentOrgName = "dataToView.companyName"
                                     :setCurrentName="{value:dataToView.companyId, label:dataToView.companyName}"></cascaderDom>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="formInline.se_date = [getCurrentMonthFirst(),getCurrentMonthLast()]">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportExcel">导出</Button>
            </i-col>
        </Row>
        <div :style="{height: height}">
            <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！" show-summary :summary-method="handleSummary" :height="height"
                   :data="infos" width="100%"  highlight-row stripe size="small"></Table>
        </div>
        <Modal v-model="modal1" width="900" :mask-closable="false" title="企业排查记录" :footer-hide="true">
            <Table ref='table' style="margin-top: 0px" :loading="loading2" border :columns="columns2" no-data-text="没有查询到相关数据！"
                   :data="infos2" width="100%" height="400" highlight-row stripe size="small"></Table>
            <Row type="flex" justify="end" >
                <i-col>
                    <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                          @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                </i-col>
            </Row>
        </Modal>
        <Modal v-model="modal2" width="900" :mask-closable="false" title="排查记录">
            <Form :label-width="130" >
                <Row >
                    <i-col>
                        <FormItem label="排查对象：">
                            {{formData.proName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row class="code-row-bg2">
                    <i-col>
                        <FormItem label="排查人所在机构：">
                            {{formData.orgName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row>
                    <i-col span="8">
                        <FormItem label="排查人：">
                            {{formData.userName}}
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="排查上报时间：">
                            {{formData.startTimeStr}}
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="排查状态：">
                            {{formData.state}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row class="code-row-bg2">
                    <i-col>
                        <FormItem label="排查结果描述：">
                            {{formData.desn}}
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <Divider orientation="left" >隐患条目</Divider>
            <Table border :columns="itemColumns" no-data-text="没有查询到相关数据！"
                   :data="itemInfos" width="100%" height="200" highlight-row stripe size="small"></Table>
            <Divider orientation="left" >隐患列表</Divider>
            <Table border :columns="inverstigationColumns" no-data-text="没有查询到相关数据！"
                   :data="inverstigationInfos" width="100%" height="200" highlight-row stripe size="small"></Table>
            <div slot="footer">
                <Button @click="modal2 = false"  class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
        <Modal v-model="modal3" width="900" :mask-closable="false" title="超时未排查记录">
            <Table ref='table' style="margin-top: 0px" :loading="loading2" border :columns="columns2" no-data-text="没有查询到相关数据！"
                   :data="infos2" width="100%" height="400" highlight-row stripe size="small"></Table>
            <div slot="footer">
                <Button @click="modal3 = false"  class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
        <Modal v-model="modal4" width="900" :mask-closable="false" title="超时未整改隐患数量">
            <Table ref='table' style="margin-top: 0px" :loading="loading2" border :columns="columns3" no-data-text="没有查询到相关数据！"
                   :data="infos2" width="100%" height="400" highlight-row stripe size="small"></Table>
            <div slot="footer">
                <Button @click="modal4 = false"  class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
        <Modal title="用户列表" v-model="visible" width="400">
            <Table  :loading="loading2" border :columns="columns4" no-data-text="没有查询到相关数据！"
                    :data="infos3" width="100%" height="300" highlight-row stripe size="small"></Table>
            <div slot="footer" >
                <Button @click="visible=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import {Api} from '../../../api'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import cascaderDom from "@/components/cascader-dom.vue"

    export default {
        name: "apsgCheckrecordCount2",
        components:{
            cascaderDom
        },
        data(){
            return{
                ifSpin: false,
                loading: false,
                loading2: false,
                modal1: false,
                modal2: false,
                modal3: false,
                modal4: false,
                visible: false,
                height: '',
                formInline:{
                    se_date: []
                },
                orgId: '',
                formData: {},
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '机构名称',
                        align: 'center',
                        key: 'orgName',
                        // render:(h,params)=>{
                        //     return h('div',[
                        //         h('a', {
                        //                 on: {
                        //                     click: () => {
                        //                         this.modal1 = true;
                        //                         this.orgId = params.row.orgId;
                        //                         this.queryCheckRecord();
                        //                     }
                        //                 }
                        //             },
                        //             params.row.orgName || '--')
                        //     ]);
                        // }
                    },
                    {
                        title: '计划排查次数',
                        align: 'center',
                        key: 'planCount',
                    },
                    {
                        title: '实际排查次数',
                        align: 'center',
                        key: 'completeCount',
                    },
                    {
                        title: '超时未排查总数',
                        align: 'center',
                        key: 'noCompleteCount',
                        render:(h,params)=>{
                            return h('div',[
                                h('a', {
                                    on: {
                                        click: () => {
                                            this.modal3 = true;
                                            this.queryTimeout(params.row.orgId);
                                        }
                                    }
                                },
                                params.row.noCompleteCount)
                            ]);
                        }
                    },
                    {
                        title: '实际排查占总体排查次数百分比',
                        align: 'center',
                        key: 'completeCountRate',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.completeCountRate || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查发现隐患数量',
                        align: 'center',
                        key: 'hiddenCount',
                    },
                    {
                        title: '手动上报隐患数量',
                        align: 'center',
                        key: 'noHiddenCount',
                    },
                    {
                        title: '超时未整改隐患数量',
                        align: 'center',
                        key: 'timeOutCount',
                        render:(h,params)=>{
                            return h('div',[
                                h('a', {
                                        on: {
                                            click: () => {
                                                this.modal4 = true;
                                                this.queryTimeoutInverstigation(params.row.orgId);
                                            }
                                        }
                                    },
                                    params.row.timeOutCount)
                            ]);
                        }
                    },
                    {
                        title: '按时整改隐患占总隐患数量百分比',
                        align: 'center',
                        key: 'timeRate',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.timeRate || '--')
                            ]);
                        }
                    },
                ],
                infos: [],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '任务名称',
                        align: 'center',
                        key: 'taskName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.taskName || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查日期',
                        align: 'center',
                        key: 'taskDate',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.taskDate || '--')
                            ]);
                        }
                    },
                    {
                        title: '限定日期',
                        align: 'center',
                        key: 'validityTime',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.validityTime || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查单位',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.orgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查岗位',
                        align: 'center',
                        key: 'positionName',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.positionName || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 120,
                        render:(h,params)=>{
                            if(params.row.userName){
                                return h('div',[
                                    h('span',params.row.userName || '--')
                                ]);
                            }else{
                                return h('div',[
                                    h('a', {
                                            on: {
                                                click: () => {
                                                    this.modal3 = true;
                                                    this.queryUserByPosition(params.row.positionId);
                                                }
                                            }
                                        },
                                        '详情')
                                ]);
                            }
                        }
                    }
                ],
                columns3: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '隐患流水号',
                        align: 'center',
                        key: 'flowNo',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.flowNo || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.userName || '--')
                            ]);
                        }
                    },
                    {
                        title: '上报日期',
                        align: 'center',
                        key: 'validityTime',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', params.row.createDate!= null ?this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd'): '--')
                            ]);
                        }
                    },
                    {
                        title: '整改限定时间',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', params.row.completionDate!= null ?this.formatDate(new Date(params.row.completionDate), 'yyyy-MM-dd'): '--')
                            ]);
                        }
                    },
                    {
                        title: '期限',
                        align: 'center',
                        key: 'positionName',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.recPeriod || '--')
                            ]);
                        }
                    }
                ],
                columns4: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        minWidth: 220,
                        title: '用户名称',
                        key: 'userName',
                        align: 'center'
                    },
                ],
                infos2: [],
                infos3: [],
                itemColumns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '状态',
                        align: 'center',
                        key: 'userName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div', [
                                h('span', {
                                    style: {
                                        color: params.row.state == 0 ? 'green': 'red'
                                    }
                                },params.row.state == 0 ? '安全': '有隐患')
                            ]);
                        }
                    },
                    {
                        title: '级别',
                        align: 'center',
                        key: 'level',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.level || '--')
                            ]);
                        }
                    },
                    {
                        title: '条目编码',
                        align: 'center',
                        key: 'code',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.code || '--')
                            ]);
                        }
                    },
                    {
                        title: '条目类型',
                        align: 'center',
                        key: 'userName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', params.row.type1 == null? '自定义隐患' : params.row.type3+'>>'+params.row.type2+'>>'+params.row.type1 || '--')
                            ]);
                        }
                    },
                    {
                        title: '条目内容',
                        align: 'center',
                        key: 'content',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.content || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查时间',
                        align: 'center',
                        key: 'reportDateStr',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.reportDateStr || '--')
                            ]);
                        }
                    },
                ],
                itemInfos: [],
                inverstigationColumns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '状态',
                        align: 'center',
                        key: 'level',
                        minWidth: 120,
                        render:(h,params)=>{
                            let color = 'green';
                            if(params.row.status == undefined || params.row.status == null){
                                color = 'red';
                            }
                            return h('div', [
                                h('span', {
                                    style: {
                                        color: color
                                    }
                                },params.row.status == 1 ? '审批中': params.row.status == 2 ? '被退回': params.row.status == 3 ? '已消除': '未上报' || '--')
                            ]);
                        }
                    },
                    {
                        title: '流水号',
                        align: 'center',
                        key: 'flowNo',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.flowNo || '--')
                            ]);
                        }
                    },
                    {
                        title: '分类',
                        align: 'center',
                        key: 'level',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', params.row.apItemType == null? '--' : params.row.type+'>>'+params.row.itemType+'>>'+params.row.apItemType || '--')
                            ]);
                        }
                    },
                    {
                        title: '级别',
                        align: 'center',
                        key: 'level',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.level || '--')
                            ]);
                        }
                    },
                    {
                        title: '内容',
                        align: 'center',
                        key: 'content',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.content || '--')
                            ]);
                        }
                    },
                    {
                        title: '描述',
                        align: 'center',
                        key: 'remark',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.remark || '--')
                            ]);
                        }
                    },],
                inverstigationInfos: [],
                dataToView: {}
            }
        },
        mounted(){
            this.height = window.innerHeight - this.$refs.table.$el.offsetTop - 255;
            this.formInline.se_date = [this.getCurrentMonthFirst(), this.getCurrentMonthLast()];
            let user = sessionStorage('userId').getObject('userId');
            this.formInline.orgId = user.companyId;
            this.dataToView = {companyName: user.companyName, companyId: user.companyId};
            setTimeout(() => {
                this.$refs.existOrg.setCurrentOrg();
            }, 100);
            this.query();
        },
        methods: {
            query(){
                let user = sessionStorage('userId').getObject('userId');
                let data = { orgId: this.formInline.orgId }
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                this.loading = true;
                this.$http.get(Api.apsgSubsidiaryCheckrecordCount, {
                    params: data
                }).then(function(res){
                    if(res.data.status == 200){
                        this.infos = res.data.data;
                    }else{
                        this.$Message.error({
                            content: '查询失败',
                            duration: 4
                        });
                    }
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            queryCheckRecord(){
                let data = {
                    proId: this.orgId,
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                };
                this.loading2 = true;
                this.$http.get(Api.apsgCheckrecord, {
                    params: data
                }).then(function(res){
                    this.infos2 = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.queryCheckRecord();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.queryCheckRecord();
            },
            exportExcel(){
                let user = sessionStorage('userId').getObject('userId');
                let data = { orgId: this.formInline.orgId };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                this.ifSpin = true;
                this.$http.get(Api.apsgSubsidiaryCheckrecordCount + '/excel',{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    this.ifSpin = false;
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "机构组织排查情况统计表.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                })
            },
            handleSummary ({ columns, data }) {
                const sums = {};
                columns.forEach((column, index) => {
                    const key = column.key;
                    if (index === 0) {
                        sums[key] = {
                            key,
                            value: '合计'
                        };
                        return;
                    }
                    const values = data.map(item => Number(item[key]));
                    if (!values.every(value => isNaN(value))) {
                        const v = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        if(key == 'completeCountRate' || key == 'timeRate'){
                            sums[key] = {
                                key,
                                value: ''
                            };
                        }else{
                            sums[key] = {
                                key,
                                value: v
                            };
                        }
                    }else {
                        sums[key] = {
                            key,
                            value: ''
                        };
                    }
                });
                return sums;
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            getCurrentMonthFirst(){
                let date = new Date();
                date.setDate(1);
                let month = parseInt(date.getMonth()+1);
                let day = date.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            },
            getCurrentMonthLast(){
                let date=new Date();
                let currentMonth=date.getMonth();
                let nextMonth=++currentMonth;
                let nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
                let oneDay=1000*60*60*24;
                let lastTime = new Date(nextMonthFirstDay-oneDay);
                let month = parseInt(lastTime.getMonth()+1);
                let day = lastTime.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            },
            setOrgName(data){
                this.formInline.orgId = data[data.length - 1];
            },
            queryTimeout(orgId){
                this.infos2 = [];
                let data = { orgId: orgId };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                this.loading2 = true;
                this.$http.get(Api.apsgTaskTimeout, {
                    params: data
                }).then(function(res){
                    if(res.data.status == 200){
                        this.infos2 = res.data.data;
                    }else{
                        this.$Message.error({
                            content: '查询失败',
                            duration: 4
                        });
                    }
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            queryTimeoutInverstigation(orgId){
                this.infos2 = [];
                let data = { orgId: orgId };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                this.loading2 = true;
                this.$http.get(Api.apsgTaskTimeout + '/inverstigation', {
                    params: data
                }).then(function(res){
                    if(res.data.status == 200){
                        this.infos2 = res.data.data;
                    }else{
                        this.$Message.error({
                            content: '查询失败',
                            duration: 4
                        });
                    }
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            queryUserByPosition(positionId){
                this.visible = true;
                this.loading2 = true;
                this.$http.get(Api.queryUsersByPositionId + positionId ).then((res) => {
                    this.loading2 = false;
                    this.infos3 = res.data.data;
                });
            },
        }
    }
</script>

<style scoped>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
